package pri.damai.xiaowu.auth.service;

import pri.damai.xiaowu.auth.enums.ResultEnum;
import pri.damai.xiaowu.auth.manager.SmsManager;
import pri.damai.xiaowu.auth.manager.UserManager;
import org.springframework.stereotype.Service;
import pri.damai.xiaowu.common.core.exception.GlobalException;

import javax.annotation.Resource;
import java.util.Optional;

/**
 *
 * @Desc
 * @Author DaMai
 * @Date 2021/10/19 13:45
 * 但行好事，莫问前程。
 */
@Service
public class SmsService {

    @Resource
    SmsManager smsManager;
    @Resource
    UserManager userManager;

    /**
     * 发送短信
     * @apiNote [附加描述]
     * @param phone 手机号
     * @author DaMai
     * @date 2021/10/19 14:06
     */
    public void sendSms(String phone) {

        Optional.ofNullable(userManager.getUserByPhone(phone))
                .orElseThrow(() -> new GlobalException(ResultEnum.USER_NOT_FOUND));

        smsManager.checkLimitRules(phone);

        String loginCode = smsManager.createRandomSmsCode();

        smsManager.sendLoginSms(phone, loginCode);

        smsManager.saveLoginCode(phone, loginCode);
    }
}
